package com.htgd.gardenexpo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeBaseUser;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.*;

import com.htgd.gardenexpo.vo.PlantIndex;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.lang.RandomStringUtils;

import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.hutool.crypto.SecureUtil.hmacMd5;

/**
 * @author ：hejing
 * @date ：Created in 2021/4/12 15:44
 * @description：通用接口
 * @menu: 通用接口
 * @modified By：`
 * @version: 1.0
 */
@EnableScheduling
@RestController
@RequestMapping("/api/v1")
@Api(tags = "通用接口")
public class GardenexpoController {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static String prKey="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIRPp3B3Ihzeip0r1aGcKXR4KJ6B3YigplZh4rYXr0u5Dd1tGAjtKscvFigTeg4pXWQOKXMBs41MlK0eRV36KpmTlO6twi0HN7a9qt2OlqZdcMuQz36fWQ_PXrfT1GsPbEG93yFEHL5VDL4kO440bwZotzWWAAMwKKpjNwrtciKtAgMBAAECgYB_jwe_bqutp4N9mbghUZvJ1NpcTpmU0kTrPP3ETjtLRsKuOjIU0QoP9D5pLrXal1iZUOn3HanMTQt9h5Sa0Mdl27XDLJ37vbItErI2L-i6KAUsr8yOTT94IIbNnjh3J9kBg2k-Yk6DCQCU6FJNbHaP_79hG1YtTdD7-HwUknqEoQJBALoJHjpYBKipbsyWuBEwvLBXS6okaNw1dp2IWDYNDjd1z50JQqKzq5PZZ4nPsim69Lo6nZ1ae1mN-Sy5q_YX_vkCQQC2EiAS4boEl3ebUJH8g11QOHrzL-h-P6Bwbb7Ki8CQNtBm7VqxKO_pboB9hQBi_6PSaWrcTLKzlYTggxA7GspVAkAiVVJ11A6wDez75wj7azI3nTTCpsuPcHJ-qk4VU51_EMgLJE1e96e_tozMOz-XQgCuaejyxGMlaPVGktGwrkcJAkB9qpD8t1QfKzRgvQGmGj1jyzgBdgWwbdYdA4J2ZnMolszM3fKE6M5-fcit2gjkS7IU3rHlEAMftImcNJoVUW5pAkBYzZUUAelGTouD65fQqVfjmAuy1JEFjOgKNjsJUnMpizA6z1UHFWr7SFXryV8oZ9xokxSqTGMR3i5WmXGS1jj8";
    public static final String authorization_code="authorization_code";

    Logger logger = LoggerFactory.getLogger(GardenexpoController.class);


    @Resource
    private GeBaseUserService geBaseUserService;

    @Resource
    private GeOuthTokenService geOuthTokenService;

    @Resource
    private WxAccessTokenService wxAccessTokenService;

    @Resource
    private GeBaseUserRoleService geBaseUserRoleService;

    @Resource
    private GeParkStateService geParkStateService;

    @Resource
    private GeAiTokenService geAiTokenService;

    @Resource
    private DdBotanyCopy1Service ddBotanyCopy1Service;

    @Resource GeParkToiletService geParkToiletService;



    /* @RequestMapping("ceshi")
    public String ceshi() throws InvalidKeySpecException, NoSuchAlgorithmException {
        Map<String, String> keyMap = RSAUtils.createKeys(1024);
        String publicKey = keyMap.get("publicKey");
        String privateKey = keyMap.get("privateKey");
        System.out.println("公钥: \n\r" + publicKey);
        System.out.println("私钥： \n\r" + privateKey);

        System.out.println("公钥加密——私钥解密");
        String str = "123456";
        System.out.println("\r明文：\r\n" + str);
        System.out.println("\r明文大小：\r\n" + str.getBytes().length);
        String encodedData = RSAUtils.publicEncrypt(str, RSAUtils.getPublicKey(publicKey));  //传入明文和公钥加密,得到密文
        System.out.println("密文：\r\n" + encodedData);
        String decodedData = RSAUtils.privateDecrypt(encodedData, RSAUtils.getPrivateKey(privateKey)); //传入密文和私钥,得到明文
        System.out.println("解密后文字: \r\n" + decodedData);
        String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCET6dwdyIc3oqdK9WhnCl0eCiegd2IoKZWYeK2F69LuQ3dbRgI7SrHLxYoE3oOKV1kDilzAbONTJStHkVd-iqZk5TurcItBze2vardjpamXXDLkM9-n1kPz16309RrD2xBvd8hRBy-VQy-JDuONG8GaLc1lgADMCiqYzcK7XIirQIDAQAB";
        String prKey="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIRPp3B3Ihzeip0r1aGcKXR4KJ6B3YigplZh4rYXr0u5Dd1tGAjtKscvFigTeg4pXWQOKXMBs41MlK0eRV36KpmTlO6twi0HN7a9qt2OlqZdcMuQz36fWQ_PXrfT1GsPbEG93yFEHL5VDL4kO440bwZotzWWAAMwKKpjNwrtciKtAgMBAAECgYB_jwe_bqutp4N9mbghUZvJ1NpcTpmU0kTrPP3ETjtLRsKuOjIU0QoP9D5pLrXal1iZUOn3HanMTQt9h5Sa0Mdl27XDLJ37vbItErI2L-i6KAUsr8yOTT94IIbNnjh3J9kBg2k-Yk6DCQCU6FJNbHaP_79hG1YtTdD7-HwUknqEoQJBALoJHjpYBKipbsyWuBEwvLBXS6okaNw1dp2IWDYNDjd1z50JQqKzq5PZZ4nPsim69Lo6nZ1ae1mN-Sy5q_YX_vkCQQC2EiAS4boEl3ebUJH8g11QOHrzL-h-P6Bwbb7Ki8CQNtBm7VqxKO_pboB9hQBi_6PSaWrcTLKzlYTggxA7GspVAkAiVVJ11A6wDez75wj7azI3nTTCpsuPcHJ-qk4VU51_EMgLJE1e96e_tozMOz-XQgCuaejyxGMlaPVGktGwrkcJAkB9qpD8t1QfKzRgvQGmGj1jyzgBdgWwbdYdA4J2ZnMolszM3fKE6M5-fcit2gjkS7IU3rHlEAMftImcNJoVUW5pAkBYzZUUAelGTouD65fQqVfjmAuy1JEFjOgKNjsJUnMpizA6z1UHFWr7SFXryV8oZ9xokxSqTGMR3i5WmXGS1jj8";
        return "ceshi";
    }*/
    /*@Value("${sms.appId}")
    private String smsAppId;

    @Value("${sms.key}")
    private String smsKey;*/
    @Value("${sms.account}")
    private String smsAccount;

    @Value("${sms.password}")
    private String smsPassword;

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${sms.sign}")
    private String smsSign;

    @Value("${outh.grant.type}")
    private String grantType;

    @Value("${outh.client.id}")
    private String clientId;

    @Value("${outh.client.secret}")
    private String clientSecret;

    @Value("${outh.redirect.uri}")
    private String redirectUri;
    @Value("${redirect.uri}")
    private String redirectUrl;
    @Value("${redirect.error}")
    private String redirectError;

    @Value("${redirect.noToken}")
    private String noToken;
    @Value("${redirect.noUserInfo}")
    private String noUserInfo;
    @Value("${redirect.unknowErro}")
    private String unknowErro;

    @Value("${outh.url.access_token}")
    private String accessTokenUrl;

    @Value("${outh.url.profile}")
    private String profileUrl;
    @Value("${face.register}")
    private String face_url;
    @Value("${face.token}")
    private String faceToken;
    @Value("${face.appKey}")
    private String faceKey;
    @Value("${face.appSecret}")
    private String faceSecret;

    @Value("${wx.public.appId}")
    public String appId;
    @Value("${wx.public.appsecret}")
    public String appsecret;
    @Value("${retail.query_url}")
    public String queryUrl;

    @Value("${retail.tran_info}")
    public String tranInfo;
    @Value("${retail.trans_query}")
    public String transQuery;

    @Value("${ticket.notify.url}")
    public String notifyUrl;

    @Value("${wx.code.url}")
    public String code_url;

    @Value("${plant.img}")
    public String plantImg;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    class SmsRunnable implements Runnable {
        public String phone = "";
        public String random = "";

        public SmsRunnable(String phone, String random) {
            this.phone = phone;
            this.random = random;
        }

        @SneakyThrows
        @Override
        public void run() {
            Thread.sleep(300000);
            if (!phone.contains(",")) {
//                String sql = "delete from ge_verification_code where phone=" + phone + " and code=" + random;
                jdbcTemplate.update("delete from ge_verification_code where phone=? and code=?",new Object[]{phone,random});
            } else {
                for (String p : phone.split(",")) {
//                    String sql = "delete from ge_verification_code where phone=" + p + " and code=" + random;
                    jdbcTemplate.update("delete from ge_verification_code where phone=? and code=?",new Object[]{p,random});
                }
            }
        }
    }

    public int calLastedTime(Date startDate) {
        long a = System.currentTimeMillis();
        long b = startDate.getTime();
        int c = (int) ((a - b) / 1000);
        return c;
    }

    /**
     * 发送短信验证码
     */
    @GetMapping(value = "/sendSMS")
    public JSONObject sendSMS(String phone) {
        JSONObject jsonObject1 = new JSONObject();
        try {
            if (!PhoneUtils.confPhone(phone)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", 300);
                jsonObject.put("message","手机号格式不正确！");
                return jsonObject;
            }
//            String query1 = "select * from ge_verification_code where phone=" + phone;
            List<Map<String, Object>> list1 = jdbcTemplate.queryForList("select * from ge_verification_code where phone=?",new Object[]{phone});
            if (list1.size() > 0) {
                Map<String, Object> map2 = list1.get(0);
                int min=calLastedTime(sdf.parse(map2.get("time").toString().split("\\.")[0]));
                if (min<60){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("code", 300);
                    jsonObject.put("message","1分钟内仅能发送一次验证码");
                    return jsonObject;
                }
            }
            String pwd = DigestUtils.md5DigestAsHex(smsPassword.getBytes(StandardCharsets.UTF_8)).toUpperCase();
            String timestamp = String.valueOf(System.currentTimeMillis());
            int random = (int) ((Math.random() * 9 + 1) * 100000);
            String params = "account=" + smsAccount + "&password=" + pwd + "&mobile=" + phone + "&content=" + URLEncoder.encode(smsSign + "本次验证码为" + random + ",有效期为5分钟，为保护您的账户安全，请妥善保管，切勿泄露。", "utf-8")+"&action=send&userid=&sendTime=&extno=";
            String result = HttpRequest.sendPost(smsUrl, params);
            if (JSON.parseObject(result).getString("returnstatus").equals("Success")){
                if (!phone.contains(",")) {
//                    String query = "select * from ge_verification_code where phone=" + phone;
                    List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from ge_verification_code where phone=?",new Object[]{phone});
                    if (list == null || list.size() == 0) {
//                        String sql = "insert into ge_verification_code(phone,code) values (" + phone + "," + random + ")";
                        jdbcTemplate.update("insert into ge_verification_code(phone,code) values (?,?)",new Object[]{phone,random});
                    } else {
//                        String sql = "update ge_verification_code set code=" + random + " where phone=" + phone;
                        jdbcTemplate.update("update ge_verification_code set code=? where phone=?",new Object[]{random,phone});
                    }
                } else {
                    for (String p : phone.split(",")) {
                        String query = "select * from ge_verification_code where phone=" + p;
                        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from ge_verification_code where phone=?",new Object[]{p});
                        if (list == null || list.size() == 0) {
//                            String sql = "insert into ge_verification_code(phone,code) values (" + p + "," + random + ")";
                            jdbcTemplate.update("insert into ge_verification_code(phone,code) values (?,?)",new Object[]{p,random});
                        } else {
//                            String sql = "update ge_verification_code set code=" + random + " where phone=" + p;
                            jdbcTemplate.update("update ge_verification_code set code=? where phone=?",new Object[]{random,p});
                        }
                    }
                }
                new Thread(new SmsRunnable(phone, String.valueOf(random))).start();
                jsonObject1.put("code", 200);
                return jsonObject1;
            }else {
                jsonObject1.put("code",300);
                jsonObject1.put("message",JSON.parseObject(result).getString("message"));
                return jsonObject1;
            }


        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            return jsonObject;
        }
    }

    /**
     * 综管单点对接通过code获取token,根据token获取用户信息
     */
    @GetMapping("/getInfoByCode")
    public void getInfoByCode(String code, HttpServletResponse response) throws IOException {
        try{
            String tokenParms="grant_type="+grantType+"&client_id="+clientId+"&client_secret="+clientSecret+"&code="+code+"&redirect_uri="+redirectUri;
            String atokens=HttpRequest.sendGet(accessTokenUrl,tokenParms);
//            System.out.println(atokens);
            if (!atokens.equals("")){
                String access_token=atokens.split("&")[0].split("=")[1];
                String parms="access_token="+access_token;
                String userinfo =HttpRequest.sendGet(profileUrl,parms);
                System.out.println(userinfo);
                JSONObject jb=JSON.parseObject(userinfo);
                if (jb.get("attributes")!=null){
                    JSONObject jbt=jb.getJSONObject("attributes");
                    if (jbt.getString("mobilePhone")!=null){
                        String phone=jbt.getString("mobilePhone");
                        List<GeBaseUser> list=geBaseUserService.getUserByPhone(phone);
                        if (list!=null&&list.size()>0){
                            GeBaseUser geBaseUser=list.get(0);
//                        System.out.println(geBaseUser.toString());
                            GeBaseUserRole geBaseUserRole=geBaseUserRoleService.queryById(geBaseUser.getUserId());
                            if (geBaseUserRole==null||geBaseUserRole.getRoleId()==29){
                                geBaseUserRole.setUserId(geBaseUser.getUserId());
                                geBaseUserRole.setRoleId(1);
                                geBaseUserRoleService.update(geBaseUserRole);
                            }
                            if (jbt.getString("userId").equals("1001")){
                                geBaseUserRole.setUserId(geBaseUser.getUserId());
                                geBaseUserRole.setRoleId(2);
                                geBaseUserRoleService.update(geBaseUserRole);
                            }
                            String token= TokenUtil.sign(geBaseUser);
                            GeOuthToken geOuthToken1=geOuthTokenService.queryById(token);
                            if (geOuthToken1==null){
                                GeOuthToken geOuthToken = new GeOuthToken();
                                geOuthToken.setAccessToken(token);
                                geOuthToken.setUserId(geBaseUser.getUserId());
                                geOuthTokenService.insert(geOuthToken);
                            }else {
                                geOuthToken1.setUserId(geBaseUser.getUserId());
                                geOuthToken1.setAccessToken(token);
                                geOuthTokenService.update(geOuthToken1);
                            }
//                        System.out.println(redirectUrl+token);
                            response.sendRedirect(redirectUrl+token);
                        }else {
                            GeBaseUser geBaseUser = new GeBaseUser();
                            geBaseUser.setUsername(jbt.getString("userName"));
                            geBaseUser.setPhone(phone);
                            geBaseUser.setDelFlag(0);
                            geBaseUserService.insert(geBaseUser);
                            GeBaseUserRole geBaseUserRole=new GeBaseUserRole();
                            if (jbt.getString("userId").equals("1001")){
                                geBaseUserRole.setUserId(geBaseUser.getUserId());
                                geBaseUserRole.setRoleId(2);
                                geBaseUserRoleService.insert(geBaseUserRole);
                            }else {
                                geBaseUserRole.setUserId(geBaseUser.getUserId());
                                geBaseUserRole.setRoleId(1);
                                geBaseUserRoleService.insert(geBaseUserRole);
                            }
                            String token= TokenUtil.sign(geBaseUser);
                            GeOuthToken geOuthToken1=geOuthTokenService.queryById(token);
                            if (geOuthToken1==null){
                                GeOuthToken geOuthToken = new GeOuthToken();
                                geOuthToken.setAccessToken(token);
                                geOuthToken.setUserId(geBaseUser.getUserId());
                                geOuthTokenService.insert(geOuthToken);
                            }else {
                                geOuthToken1.setUserId(geBaseUser.getUserId());
                                geOuthToken1.setAccessToken(token);
                                geOuthTokenService.update(geOuthToken1);
                            }
                            response.sendRedirect(redirectUrl+token);
                        }
                    }else {
                        if (jbt.getString("userName")!=null){
                            response.sendRedirect(redirectError+java.net.URLEncoder.encode(jbt.getString("userName"),"UTF-8"));
                        }else {
                            response.sendRedirect(noUserInfo);
                        }
                    }
                }else {
                    response.sendRedirect(noUserInfo);
                }
            }else {
                response.sendRedirect(noToken);
            }
        }catch (Exception e){
            e.printStackTrace();
            response.sendRedirect(unknowErro);
        }
    }
    @GetMapping("umsDailySaleQuery")
    public String umsDailySaleQuery(){
       /* JSONObject json=new JSONObject();
        json.put("appKey","chinaumsandroidpos");
        json.put("methodVer","1.0");
        json.put("nonceStr","D1K2");
        json.put("mobileNo","18102160080");
        String ss= SHAUtils.getSign(json.toString(),"xx123","UTF-8");
        json.put("sign",ss);
        String result=HttpRequest.sendPost("http://db1test.ngrok2.xiaomiqiu.cn/ums-openApi/vipQueryApi",json.toString(),"xx123");
        return result;*/
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("mobileNo", "18822091581");
        bodyParams.put("timeBegin", "2021-08-03");
        bodyParams.put("timeEnd", "2021-08-11");
        bodyParams.put("pageNo", 1);
        bodyParams.put("pageSize", 10);


        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
//        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(transQuery,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        System.out.println(result);
        return result;
    }


    /**
     *  AI步道人脸判定
     */
    @GetMapping(value = "/faceRegister")
    public CommonResult<JSONObject> faceRegister(String faceUrl,String phone){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeAiToken geAiToken=geAiTokenService.queryById(1);
            String token = geAiToken.getToken();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("nonce",RandomStringUtils.randomAlphanumeric(10));
            jsonObject.put("timestamp",System.currentTimeMillis());
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("faceUrl",faceUrl);
            jsonObject1.put("phone",phone);
            jsonObject1.put("gender",0);
            jsonObject.put("payload",jsonObject1);
//            System.out.println(jsonObject.toString());
//            System.out.println( hmacMd5(geAiToken.getScrect()).digestHex(jsonObject.toString()));
            String md5= hmacMd5(geAiToken.getScrect()).digestHex(jsonObject.toString());
//            String params="faceUrl="+faceUrl+"&phone="+phone;
            String res=HttpRequest.sendPost(face_url,jsonObject.toString(),"face.register.register",md5,token);
            System.out.println(res);
            JSONObject jsonObject2=JSON.parseObject(res);
            if (jsonObject2.getInteger("code")==0){
                result.setCode(0);
            }else {
                result.setCode(300);
                result.setMessage(jsonObject2.getString("message"));
            }
//            result.setData(JSON.parseObject(res));
//            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     *  AI步道人脸判定
     */
    @GetMapping(value = "/faceRegisterWx")
    public CommonResult<JSONObject> faceRegisterWx(String faceUrl,String phone){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeAiToken geAiToken=geAiTokenService.queryById(1);
            String token = geAiToken.getToken();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("nonce",RandomStringUtils.randomAlphanumeric(10));
            jsonObject.put("timestamp",System.currentTimeMillis());
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("faceUrl",faceUrl);
            jsonObject1.put("phone",phone);
            jsonObject1.put("gender",0);
            jsonObject.put("payload",jsonObject1);
//            System.out.println(jsonObject.toString());
//            System.out.println( hmacMd5(geAiToken.getScrect()).digestHex(jsonObject.toString()));
            String md5= hmacMd5(geAiToken.getScrect()).digestHex(jsonObject.toString());
//            String params="faceUrl="+faceUrl+"&phone="+phone;
            String res=HttpRequest.sendPost(face_url,jsonObject.toString(),"face.register.register",md5,token);
            System.out.println(res);
            JSONObject jsonObject2=JSON.parseObject(res);
            if (jsonObject2.getInteger("code")==0){
                result.setCode(0);
            }else {
                result.setCode(300);
                result.setMessage(jsonObject2.getString("message"));
            }
//            result.setData(JSON.parseObject(res));
//            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取AI步道token
     */
//    @Scheduled(cron = "0 0 0/2 * * ?")
    @GetMapping("/getfaceAiToken")
    public void getfaceAiToken(){
        String parmas="appKey="+faceKey+"&appSecret="+faceSecret;
        String s=HttpRequest.sendPost(faceToken,parmas);
        JSONObject jsonObject= JSON.parseObject(s);
        if (jsonObject.getInteger("code")==0){
            GeAiToken geAiToken=geAiTokenService.queryById(1);
            if (geAiToken!=null){
                geAiToken.setToken(jsonObject.getJSONObject("data").getString("token"));
                geAiToken.setScrect(jsonObject.getJSONObject("data").getString("secret"));
                geAiTokenService.update(geAiToken);
            }else {
                GeAiToken geAiToken1 = new GeAiToken();
                geAiToken1.setToken(jsonObject.getJSONObject("data").getString("token"));
                geAiToken1.setScrect(jsonObject.getJSONObject("data").getString("secret"));
                geAiTokenService.insert(geAiToken1);
            }
        }
    }

    @PostMapping("/notifyIndo")
    public String notifyIndo(String targetOrderId,String merOrderId,String targetSys,String status){
        logger.warn(targetOrderId+"---"+merOrderId+"---status---"+status);
        String urlString = notifyUrl;
        try {
            if (status.equals("TRADE_REFUND")){
                return "SUCCESS";
            }else {
                String s= HttpRequest.sendPost(urlString,"outTradeNo="+merOrderId+"&transactionId="+targetOrderId+"&targetSys="+targetSys);
                logger.warn("result--+"+s);
                return "SUCCESS";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "FAILED";
        }
    }

    /**
     * 获取微信签名
     */
    @GetMapping("/getTicketSign")
    public CommonResult<JSONObject> getTicketSign(String url){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            JSONObject jsonObject = new JSONObject();
            WxAccessToken wxAccessToken=wxAccessTokenService.queryById(1);
            Long timestamp=System.currentTimeMillis()/1000;
            String noncestr= RandomStringUtils.randomAlphanumeric(16);
            String parms="jsapi_ticket="+wxAccessToken.getTicket()+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
            String signature=shaEncode(parms);
            jsonObject.put("timestamp",timestamp);
            jsonObject.put("noncestr",noncestr);
            jsonObject.put("signature",signature);
            result.setCode(200);
            result.setData(jsonObject);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
    public static String shaEncode(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }


    /*@Scheduled(cron = "0 0 0/3 * * ?")
    @Scheduled(cron = "0 30 1/3 * * ?")*/
    //todo
//    @GetMapping("/getWxAccesstoken")
    public void getWxAccesstoken(){
        try {
//            System.out.println("定时任务---"+new Date());
            String params="grant_type=client_credential&appid="+appId+"&secret="+appsecret;
            String result=HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token",params);
            JSONObject jsonObject=JSON.parseObject(result);
            String pams="access_token="+jsonObject.getString("access_token")+"&type=jsapi";
            String sss=HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket",pams);
            JSONObject jsonObject1=JSON.parseObject(sss);
            WxAccessToken wxAccessToken=wxAccessTokenService.queryById(1);
            if (wxAccessToken!=null){
                wxAccessToken.setAccessToken(jsonObject.getString("access_token"));
                wxAccessToken.setExpiresIn(jsonObject.getString("expires_in"));
                wxAccessToken.setTicket(jsonObject1.getString("ticket"));
                wxAccessToken.setCreateTime(new Date());
                wxAccessTokenService.update(wxAccessToken);
            }else {
                WxAccessToken wxAccessToken1 = new WxAccessToken();
                wxAccessToken1.setAccessToken(jsonObject.getString("access_token"));
                wxAccessToken1.setExpiresIn(jsonObject.getString("expires_in"));
                wxAccessToken1.setTicket(jsonObject1.getString("ticket"));
                wxAccessTokenService.insert(wxAccessToken1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
 /*  @Scheduled(cron = "0 0/3 * * * ?")
    @Scheduled(cron = "30 1/3 * * * ?")
    public void test(){
        System.out.println(new Date()+"---123123");
    }
*/
    @Autowired
    public void run(ApplicationArguments args) throws Exception {
        getWxAccesstoken();
//        test();
    }

//    @GetMapping("/test")
    public JSONObject test(String orderNo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo",orderNo);
        String password = "06021020";
        System.out.println(jsonObject.toString());
        DesPKCS7Encrypter encrypter = new DesPKCS7Encrypter(password.getBytes(), password.getBytes());
        ByteArrayInputStream bais = new ByteArrayInputStream(jsonObject.toString().getBytes("utf-8"));
        // 声明加密输出
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Base64 加密实例
        BASE64Encoder base64Encoder = new BASE64Encoder();

        //加密
        encrypter.encrypt(bais, baos);

        //Base64加密
        String des = base64Encoder.encode(baos.toByteArray());
        des = des.replace("\r\n", "");
        long time1 = System.currentTimeMillis() / 1000;
//        String strs="815c2058-c7e5-4842-9489-2ede44758fd9GetProductInfo"+"1464183404"+"v1.0"+des+"test1234";
        String strs = "admin" + "GetOrderInfoByorderNo" + time1 + "v1.0" + des + "06021020";
        String md5 = DigestUtils.md5DigestAsHex(strs.getBytes());
        String json = "{\"requestHead\":{\"user_id\":\"" + "admin" + "\",\"method\":\"" + "GetOrderInfoByorderNo" + "\"," +
                "\"timestamp\":" + time1 + ",\"version\":\"v1.0\",\"sign\":\"" + md5 + "\"}," +
                "\"requestBody\":\"" + des + "\"}";
        System.out.println(JSON.parseObject(json));
        String urlString = "http://61.177.215.189:58210/Service/ProcessRequest";
        String s= HttpRequest.sendPost(urlString,json);
        System.out.println(JSON.parseObject(s));
        return JSON.parseObject(s);
    }

    /**
     * 获取停车场车位信息
     */
    @GetMapping(value = "/getCurrentParkAnalysis")
    public CommonResult<JSONObject> getCurrentParkAnalysis(){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeParkState geParkState=geParkStateService.queryById(1);
            result.setCode(200);
            result.setData(JSON.parseObject((String) geParkState.getParkAnalysis()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
    /**
     * 获取卫生间信息
     */
    @GetMapping(value = "/getParkToiletInfo")
    public CommonResult<JSONArray> getParkToiletInfo(){
        CommonResult<JSONArray> result = new CommonResult<>();
        try {
            GeParkState geParkState=geParkStateService.queryById(1);
            result.setCode(200);
            result.setData(JSONArray.parseArray((String) geParkState.getParkToilet()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取环境指标信息
     */
    @GetMapping(value = "/getTemAndNum")
    public CommonResult<JSONObject> getTemAndNum(){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeParkState geParkState=geParkStateService.queryById(1);
            result.setCode(200);
            result.setData(JSON.parseObject((String) geParkState.getTemandhum()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取环境指标信息
     */
    @GetMapping(value = "/getTemAndNumWx")
    public CommonResult<JSONObject> getTemAndNumWx(){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeParkState geParkState=geParkStateService.queryById(1);
            result.setCode(200);
            result.setData(JSON.parseObject((String) geParkState.getTemandhum()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取进园、在园人数
     */
    @GetMapping(value = "/getParkPeople")
    public CommonResult<JSONObject> getParkPeople(){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeParkState geParkState=geParkStateService.queryById(1);
            result.setCode(200);
            result.setData(JSON.parseObject((String) geParkState.getParkPeople()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取进园、在园人数
     */
    @GetMapping(value = "/getParkPeopleWx")
    public CommonResult<JSONObject> getParkPeopleWx(){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeParkState geParkState=geParkStateService.queryById(1);
            result.setCode(200);
            result.setData(JSON.parseObject((String) geParkState.getParkPeople()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

//    @Scheduled(cron = "0 0/10 * * * ?")
//    @GetMapping("/getParkState")
    public void getParkState(){
        String s=HttpRequest.sendGet("https://zg.xzyby.cn/zgpc/proxy/api/monitor/getParkPeople","");
        String s1=HttpRequest.sendGet("https://zg.xzyby.cn/zgpc/proxy/api/monitor/getTemAndHum","");
        String s2=HttpRequest.sendGet("https://zg.xzyby.cn/zgpc/proxy/api/parkAnalysis/getCurrentParkAnalysis","");
        GeParkState geParkState=geParkStateService.queryById(1);
        System.out.println(s);
        System.out.println(s1);
        System.out.println(s2);
        if(s!=null&&s1!=null&&s2!=null){
            JSONObject jsonObject=JSON.parseObject(s2);
            JSONArray jsonArray=jsonObject.getJSONArray("data");
            for (int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject1=jsonArray.getJSONObject(i);
                jsonObject1.put("theId",jsonObject1.getString("theId"));
            }
            if (geParkState==null){
                GeParkState geParkState1 = new GeParkState();
                geParkState1.setParkAnalysis(jsonObject.toString());
                geParkState1.setParkPeople(s);
                geParkState1.setTemandhum(s1);
                geParkStateService.insert(geParkState1);
            }else {
                geParkState.setParkAnalysis(jsonObject.toString());
                geParkState.setParkPeople(s);
                geParkState.setTemandhum(s1);
                geParkStateService.update(geParkState);
            }
        }

    }


//    @Scheduled(cron = "0 0/5 * * * ?")
    @GetMapping("/getParkToilet")
    public void getParkToilet(){
        String s=HttpRequest.sendGet("https://zg.xzyby.cn/zgpc/proxy/api/people/getToilet","");
        if (s!=null){
            JSONObject jsonObject=JSON.parseObject(s);
            JSONArray jsonArray=jsonObject.getJSONArray("data");
            JSONArray list = new JSONArray();
            for (int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject1=jsonArray.getJSONObject(i);
                JSONObject jsonObject2 = new JSONObject();
                String sn=jsonObject1.getString("sn");
                GeParkToilet geParkToilet=geParkToiletService.queryById(sn);
                jsonObject2.put("parkName",geParkToilet.getName());
                jsonObject2.put("theId",sn);
                if (jsonObject1.getString("male")!=null){
                    int m=0;
                    int mc=0;
                    for(String str:jsonObject1.getJSONObject("male").getJSONObject("extension").keySet()){
                        mc=mc+1;
                        if (jsonObject1.getJSONObject("male").getJSONObject("extension").getString(str).equals("0")){
                            m=m+1;
                        }
                    }
                    jsonObject2.put("male",m+"/"+mc);
                }
                if (jsonObject1.getString("female")!=null){
                    int f=0;
                    int fc=0;
                    for(String str:jsonObject1.getJSONObject("female").getJSONObject("extension").keySet()){
                        fc=fc+1;
                        if (jsonObject1.getJSONObject("female").getJSONObject("extension").getString(str).equals("0")){
                            f=f+1;
                        }
                    }
                    jsonObject2.put("female",f+"/"+fc);
                }

                if (jsonObject1.getString("third")!=null){
                    int t=0;
                    int tc=0;
                    for(String str:jsonObject1.getJSONObject("third").getJSONObject("extension").keySet()){
                        tc=tc+1;
                        if (jsonObject1.getJSONObject("third").getJSONObject("extension").getString(str).equals("0")){
                            t=t+1;
                        }
                    }
                    jsonObject2.put("third",t+"/"+tc);
                }
                list.add(jsonObject2);

            }
            GeParkState geParkState=geParkStateService.queryById(1);
            if (geParkState!=null){
                if (list!=null&&list.size()>0){
                    geParkState.setParkToilet(list.toString());
                    geParkStateService.update(geParkState);
                }
            }else {
                GeParkState geParkState1 = new GeParkState();
                geParkState1.setParkToilet(list.toString());
                geParkStateService.insert(geParkState1);
            }
        }

    }

    @GetMapping("/decodeUserInfo")
    public JSONObject decodeUserInfo(String appid, String js_code) {
        String params = "appid=" + appid + "&secret=fd9d3c4361f4a6f053519ff1c70e03af&js_code=" + js_code + "&grant_type="
                + authorization_code;
        String sr = HttpRequest.sendGet(code_url, params);
        try {
            // 解析相应内容（转换成json对象）
            JSONObject json = JSON.parseObject(sr);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /*@PostMapping("outLog")
    public void outLog(String s){
        System.out.println("-----"+s);
    }*/

    /**
     * 获取植物百科索引
     */
    @GetMapping(value = "/getPlantIndex")
    @ApiOperation("获取植物百科索引")
    public CommonResult<List<PlantIndex>> getPlantIndex(){
        CommonResult<List<PlantIndex>> result = new CommonResult<>();
        List<PlantIndex> plantIndexList = new ArrayList<>();
        try {
            List<DdBotanyCopy1> list=ddBotanyCopy1Service.queryAll();
            for (DdBotanyCopy1 ddBotanyCopy1:list){
                PlantIndex plantIndex = new PlantIndex();

                char firstLetter =getFirstLetter( ddBotanyCopy1.getNameZh());
                plantIndex.setIndex(String.valueOf(firstLetter));
                plantIndex.setName_zh(ddBotanyCopy1.getId());
                plantIndex.setUrl(ddBotanyCopy1.getFileName());

                plantIndexList.add(plantIndex);
//                ddBotanyCopy1.setImgUrl(plantImg+ddBotanyCopy1.getBucketName()+"-"+ddBotanyCopy1.getFileName());
            }
            result.setCode(200);
            result.setData(plantIndexList);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    public static char getFirstLetter(String chinese) {
        char firstLetter = ' '; // 默认为空格

        // 判断字符串是否为中文
        if (chinese != null && !chinese.trim().isEmpty()) {
            char[] chars = chinese.toCharArray();
            // 获取第一个字符的拼音数组
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(chars[0]);
            if (pinyinArray != null && pinyinArray.length > 0) {
                // 获取拼音的首字母并转换为大写
                firstLetter = Character.toUpperCase(pinyinArray[0].charAt(0));
            }
        }

        return firstLetter;
    }

    /**
     * 获取植物百科
     */
    @GetMapping(value = "/getAllPlant")
    @ApiOperation("获取植物百科")
    public CommonResult<Map<String,List<DdBotanyCopy1>>> getAllPlant(@RequestParam(required = false,name = "index") String index){
        CommonResult<Map<String,List<DdBotanyCopy1>>> result = new CommonResult<>();
        Map<String,List<DdBotanyCopy1>> map = new HashMap<>();
        try {
            List<DdBotanyCopy1> list=new ArrayList<>();
            if(index !=null && !(index.equals(""))){
                list=ddBotanyCopy1Service.queryByIndex(index);
                String[] split = index.split(",");
                for (String s : split) {
                    List<DdBotanyCopy1> botanyCopy1s = new ArrayList<>();
                    for (DdBotanyCopy1 ddBotanyCopy1 : list) {
                        if(ddBotanyCopy1.getIndex().equals(s)){
                            botanyCopy1s.add(ddBotanyCopy1);
                        }
                    }
                    map.put(s,botanyCopy1s);
                }

            }else {
                StringBuilder S = new StringBuilder();

                for (char c = 'A'; c <= 'Z'; c++) {
                    // 将当前字母添加到结果字符串中
                    S.append(c);

                    // 如果不是最后一个字母，则添加逗号
                    if (c != 'Z') {
                        S.append(",");
                    }
                }
                list=ddBotanyCopy1Service.queryAll();
                String[] split = String.valueOf(S).split(",");
                for (String s : split) {
                    List<DdBotanyCopy1> botanyCopy1s = new ArrayList<>();
                    for (DdBotanyCopy1 ddBotanyCopy1 : list) {
                        if(ddBotanyCopy1.getIndex().equals(s)){
                            botanyCopy1s.add(ddBotanyCopy1);
                        }
                    }
                    map.put(s,botanyCopy1s);
                }
            }
//            for (DdBotanyCopy1 ddBotanyCopy1:list){
//                ddBotanyCopy1.setImgUrl(plantImg+ddBotanyCopy1.getBucketName()+"-"+ddBotanyCopy1.getFileName());
//            }
            result.setCode(200);
            result.setData(map);
            result.setMessage(String.valueOf(list.size()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 植物百科详情
     */
    @PostMapping(value = "/getPlantInfoById")
    @ApiOperation("植物百科详情")
    @SecurityParameter
    public CommonResult<Map<String, Object>> getPlantInfoById(@RequestBody String s){
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        try {
            String id=JSON.parseObject(s).getString("id");
            Map<String, Object> map = new HashMap<>();
            DdBotanyCopy1 ddBotanyCopy1=ddBotanyCopy1Service.queryById(id);
            ddBotanyCopy1.setImgUrl(plantImg+ddBotanyCopy1.getBucketName()+"-"+ddBotanyCopy1.getFileName());
            map.put("plant",ddBotanyCopy1);
//            List<DdBotanyCopy1> list=ddBotanyCopy1Service.queryAll();
//            for (int i=0;i<list.size();i++){
//                DdBotanyCopy1 ddBotanyCopy11=list.get(i);
//                if (ddBotanyCopy11.getId().equals(id)){
//                    if (i==0){
//                        map.put("up","");
//                        map.put("down",list.get(i+1));
//                    }else if (i+1==list.size()){
//                        map.put("up",list.get(i-1));
//                        map.put("down","");
//                    }else {
//                        map.put("up",list.get(i-1));
//                        map.put("down",list.get(i+1));
//                    }
//                }
//            }
            result.setCode(200);
            result.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    @GetMapping("/updateUserTrail")
    public CommonResult<JSONObject> updateUserTrail(){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String query="update ge_base_user set trail=null";
            jdbcTemplate.execute(query);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
    @GetMapping("/gettime")
    public String gettime(){
        return new Date().toString();
    }

    @GetMapping("/addzd")
    public boolean addzd(){

       try {
           String add="ALTER TABLE ge_con_news add editor_id INT null,add publisher_id int null";
           jdbcTemplate.execute(add);
       }catch (Exception e){
           e.printStackTrace();
           return false;
       }
       return true;
    }

    @GetMapping("/addtable")
    public boolean addtable(){
        try {
            String add="create table ge_con_news_access (id int primary key not null auto_increment,news_id int not null)";
            jdbcTemplate.execute(add);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

}